<template>
  <Drawer
    width="50%"
    :title="title"
    placement="right"
    v-model:visible="visible"
    :footer-style="{ textAlign: 'right' }"
    :destroy-on-close="true"
    @afterVisibleChange="init"
    @close="close"
  >
    <template #closeIcon>
      <ArrowLeftOutlined />
    </template>

    <Form :model="formState" v-bind="formItemLayout" ref="formRef">
      <Row :gutter="16">
        <Col :span="12">
          <FormItem
            label="企业名称"
            name="alias"
            :rules="title == '查看详情' ? [] : [{ required: true, message: '请输入企业名称' }]"
          >
            <template v-if="title !== '查看详情'"
              ><Input v-model:value="formState.alias" placeholder="请输入" /></template
            ><template v-else>{{ formState.alias }}</template>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem
            label="英文名称"
            name="name"
            :rules="
              title !== '新增企业'
                ? []
                : [
                    { required: true, message: '请输入企业英文名称' },
                    {
                      pattern: /[A-Za-z0-9-]{1,63}/,
                      message: '请输入正确的企业英文名称',
                    },
                  ]
            "
          >
            <template v-if="title == '新增企业'"><Input v-model:value="formState.name" placeholder="请输入" /></template
            ><template v-else>{{ formState.name }}</template>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :span="12" v-if="title !== '新增企业'">
          <FormItem label="企业编码">
            {{ formState.code }}
          </FormItem>
        </Col>
        <Col :span="12" v-if="formState.type !== 2">
          <FormItem
            label="所属行业"
            name="industry"
            :rules="title == '查看详情' ? [] : [{ required: true, message: '请选择所属行业' }]"
          >
            <template v-if="title !== '查看详情' && formState.type !== 2">
              <Select v-model:value="formState.industry" placeholder="请选择">
                <SelectOption :key="industry.code" v-for="industry in industryOpt" :value="industry.name">{{
                  industry.name
                }}</SelectOption></Select
              ></template
            ><template v-else>{{ formState.industry }}</template>
          </FormItem>
        </Col>
        <Col :span="12" v-if="formState.type !== 2">
          <FormItem
            label="所在地"
            name="location"
            :rules="title == '查看详情' ? [] : [{ required: true, message: '请选择所属行业' }]"
          >
            <template v-if="title !== '查看详情' && formState.type !== 2">
              <Select v-model:value="formState.location" placeholder="请选择">
                <SelectOption :key="location.code" v-for="location in locationOpt" :value="location.name">{{
                  location.name
                }}</SelectOption></Select
              ></template
            ><template v-else>{{ formState.location }}</template>
          </FormItem>
        </Col>
        <Col :span="12" v-if="formState.type !== 2">
          <FormItem
            label="来源渠道"
            name="channel"
            :rules="title == '查看详情' ? [] : [{ required: true, message: '请选择来源渠道' }]"
          >
            <template v-if="title !== '查看详情' && formState.type !== 2">
              <Select v-model:value="formState.channel" placeholder="请选择">
                <SelectOption :key="channel.code" v-for="channel in channelOpt" :value="channel.name">{{
                  channel.name
                }}</SelectOption></Select
              ></template
            ><template v-else>{{ formState.channel }}</template>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :span="12">
          <FormItem
            label="管理员名称"
            name="userName"
            :rules="title !== '新增企业' ? [] : [{ required: true, message: '请输入管理员名称' }]"
          >
            <template v-if="title == '新增企业'"
              ><Input v-model:value="formState.userName" placeholder="请输入" /></template
            ><template v-else>{{ formState.userName }}</template>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16" v-if="title !== '查看详情'">
        <Col :span="12">
          <FormItem
            label="密码"
            name="password"
            :rules="title === '查看详情' || isPwdEditable === false ? [] : pwdRule"
          >
            <template v-if="title !== '新增企业' && isPwdEditable == false"
              >{{ formState.password }}
              <a @click="eidtPassword" v-if="title == '编辑企业信息' && isPwdEditable == false"><EditOutlined /></a
            ></template>
            <template v-if="title == '新增企业' || isPwdEditable == true"
              ><InputPassword v-model:value="formState.password" placeholder="请输入" @change="pwdChange"
            /></template>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem
            label="确认密码"
            v-if="(title == '编辑企业信息' && isPwdEditable == true) || title == '新增企业'"
            name="checkPassword"
            :rules="
              title == '查看详情'
                ? []
                : [
                    { required: true, message: '请输入确认密码' },
                    { validator: validatePass2, trigger: 'change' },
                  ]
            "
          >
            <InputPassword v-model:value="formState.checkPassword" placeholder="请输入" />
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :span="12">
          <FormItem label="手机号" name="phone" :rules="title == '查看详情' ? [] : rules"
            ><template v-if="title !== '新增企业' && !isPhoneEditable"
              >{{ formState.phone }}
              <span v-per="'show'"
                ><a @click="useDecrytion('phone')" v-if="phoneEyeTag"
                  ><EyeOutlined /><Divider type="vertical" v-if="title == '编辑企业信息'" /></a></span
              ><a @click="eidtPhone" v-if="title == '编辑企业信息' && !isPhoneEditable"><EditOutlined /></a
            ></template>
            <template v-if="title == '新增企业' || isPhoneEditable"
              ><Input v-model:value="formState.phone" placeholder="请输入"
            /></template>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem label="邮箱" name="email" :rules="title == '查看详情' ? [] : rules2"
            ><template v-if="title !== '新增企业' && !isEmailEditable"
              >{{ formState.email }}
              <span v-per="'show'"
                ><a @click="useDecrytion('email')" v-if="emailEyeTag && formState.email"
                  ><EyeOutlined /><Divider type="vertical" v-if="title == '编辑企业信息'" /></a></span
              ><a @click="eidtEmail" v-if="title == '编辑企业信息' && !isEmailEditable"><EditOutlined /></a
            ></template>
            <template v-if="title == '新增企业' || isEmailEditable"
              ><Input v-model:value="formState.email" placeholder="请输入"
            /></template>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :span="12" v-if="title !== '新增企业' && formState.isBuiltIn === false">
          <FormItem label="注册时间">
            {{ registerTime }}
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem
            label="过期时间"
            name="expireTimeDjs"
            :rules="showMaxDate == true || title == '查看详情' ? [] : [{ required: true, message: '请选择过期时间' }]"
          >
            <template v-if="showMaxDate == false && title !== '查看详情'"
              ><DatePicker
                v-model:value="formState.expireTimeDjs"
                placeholder="请选择"
                :disabled-date="title == '新增企业' ? disabledDate1 : disabledDate2"
                :showToday="false"
                :defaultPickerValue="title == '新增企业' ? dayjs() : dayjs(originExpireTime)"
                style="width: 293px"
            /></template>
            <template v-if="showMaxDate == true || title == '查看详情'">{{ formState.expireTime }}</template>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :span="12">
          <FormItem
            label="管理面部署策略"
            name="deployStrategy"
            :rules="title !== '新增企业' ? [] : [{ required: true, message: '请选择管理面部署策略' }]"
            ><template v-if="title !== '新增企业'">{{
              formState.deployStrategy == 'shared' ? '共享' : '独享'
            }}</template
            ><template v-else
              ><RadioGroup v-model:value="formState.deployStrategy" name="radioGroup">
                <Radio value="shared">共享</Radio>
                <Radio value="exclusive">独享</Radio>
              </RadioGroup></template
            >
          </FormItem>
        </Col>
        <Col v-if="title !== '新增企业'" :span="12">
          <FormItem
            label="是否启用"
            name="enabled"
            :rules="formState.type == 2 || title == '查看详情' ? [] : [{ required: true, message: '请选择是否启用' }]"
          >
            <template v-if="title !== '查看详情'"
              ><Switch
                v-model:checked="formState.enabled"
                checked-children="是"
                un-checked-children="否"
                :disabled="formState.type == 2" /></template
            ><template v-else>{{ formState.enabled ? '是' : '否' }}</template></FormItem
          >
        </Col>
      </Row>
      <div style="margin-left: -238px; width: 1160px">
        <FormItem label="证件照片"
          ><Upload
            v-model:file-list="files"
            list-type="picture-card"
            :beforeUpload="beforeUpload"
            :headers="{ 'Content-Type': 'multipart/form-data' }"
            @preview="handlePreview"
            @remove="handleRemove"
            v-if="title !== '查看详情'"
          >
            <div v-if="files && files.length < 5">
              <PlusOutlined />
              <div style="margin-top: 8px">Upload</div>
            </div>
          </Upload>
          <TypographyText type="secondary" v-if="title !== '查看详情'"
            >请上传证件图片，最多可上传5张，仅支持JPG，PNG格式，大小不超过100MB</TypographyText
          >
          <Modal :visible="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
            <img alt="example" style="width: 100%" :src="previewImage" v-if="title !== '查看详情'" />
          </Modal>
          <template v-if="title == '查看详情'">
            <Image v-for="item in filesInDetail" :key="item" :width="200" :src="item.url"
          /></template>
        </FormItem>
      </div>
    </Form>
    <template #footer v-if="title !== '查看详情'">
      <Button style="margin-right: 8px" type="primary" @click="submit">{{ ButtonEnum.SUBMIT }}</Button>
      <Button @click="close">{{ ButtonEnum.CANCEL }}</Button>
    </template>
  </Drawer>
</template>
<script lang="ts" setup>
import {
  Drawer,
  Form,
  FormItem,
  message,
  Button,
  SelectOption,
  Select,
  Input,
  RadioGroup,
  Radio,
  Row,
  Col,
  Switch,
  Upload,
  Modal,
  DatePicker,
  InputPassword,
  Divider,
  TypographyText,
  Image,
} from 'ant-design-vue';
import { nextTick, ref } from 'vue';
import { ArrowLeftOutlined, EditOutlined, PlusOutlined, EyeOutlined } from '@ant-design/icons-vue';
import { getLabelList } from '/@/api/sys/user';
import {
  updateEntMgt,
  getDecrytion,
  getEntDetail,
  proxyRegister,
} from '/@/api/tenant-mgmt/enterpriseManagement/enterpriseManagement';
import type { UploadProps } from 'ant-design-vue';
import { UpdateEntMgtParam } from '/@/api/tenant-mgmt/enterpriseManagement/model/enterpriseManagementModel';
import dayjs, { Dayjs } from 'dayjs';
import { Rule } from 'ant-design-vue/lib/form';
import { ApiResultEnum } from '/@/enums/resEnum';
import { ButtonEnum } from '/@/enums/buttonEnum';
const visible = ref(false);
const formState = ref({} as UpdateEntMgtParam);
const formRef = ref();
const industryOpt = ref([]);
const locationOpt = ref([]);
const channelOpt = ref([]);
const registerTime = ref();
const getInfoData = async () => {
  let data = await getLabelList();
  industryOpt.value = data.industry;
  locationOpt.value = data.location;
  channelOpt.value = data.channel;
};
const title = ref();
const isPwdEditable = ref(false);
const isPhoneEditable = ref(false);
const isEmailEditable = ref(false);
const recordId = ref();
const tenantCode = ref();

const phoneEyeTag = ref(true);
const emailEyeTag = ref(true);
const initEyeTag = () => {
  phoneEyeTag.value = true;
  emailEyeTag.value = true;
};
const originExpireTime = ref();
const disabledDate1 = (current: Dayjs) => {
  return (current && current < dayjs().endOf('day')) || current > dayjs('9999-12-31 23:59:59');
};

const disabledDate2 = (current: Dayjs) => {
  return current < dayjs(originExpireTime.value).endOf('day') || current > dayjs('9999-12-31 23:59:59');
};
const files = ref([]);
const showMaxDate = ref(false);
const ifShowMaxDate = (expireTime: string | undefined) => {
  if (expireTime == '9999-12-31 23:59:59') {
    showMaxDate.value = true;
  } else {
    showMaxDate.value = false;
    originExpireTime.value = expireTime;
    formState.value.expireTimeDjs = dayjs(expireTime);
  }
};
const openEdit = async (tenantId, email, expireTime) => {
  initEyeTag();
  let record = await getEntDetail(tenantId);
  registerTime.value = dayjs(record.registerTime).format('YYYY-MM-DD HH:mm:ss');
  recordId.value = tenantId;
  tenantCode.value = record.code;
  title.value = '编辑企业信息';
  visible.value = true;
  files.value = record.imagesList;
  formState.value = record;
  if (record.expireTime !== null) {
    ifShowMaxDate(expireTime);
  } else {
    originExpireTime.value = dayjs();
    formState.value.expireTimeDjs = undefined;
  }
  if (email && email !== 'null' && email !== 'undefined') {
    formState.value.email = email;
  } else {
    isEmailEditable.value = true;
    formState.value.email = undefined;
  }

  getInfoData();
};
const rules = ref<any>([]);
const rules2 = ref<any>([]);
const pwdRule = ref([
  { required: true, message: '请输入密码' },
  {
    pattern: /[a-zA-Z\d!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]{8,18}/,
    message: '请输入密码长度为8-18位,包含大小写字母、数字和特殊字符4类至少3类',
  },
]);
let validatePass2 = async (_rule: Rule, value: string) => {
  if (value && value !== formState.value.password) {
    return Promise.reject(new Error('请输入相同密码'));
  } else {
    return Promise.resolve();
  }
};
const pwdChange = async () => {
  if (formState.value.checkPassword) {
    await formRef.value.validateFields(['checkPassword']);
  }
};
function setPhoneRule() {
  if (isPhoneEditable.value) {
    rules.value = [
      { required: isPhoneEditable.value, message: '请输入手机号码', trigger: 'change' },
      {
        pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/,
        message: '请输入正确的手机号码',
      },
    ];
  } else {
    rules.value = [];
  }
}
function setEmailRule() {
  if (isEmailEditable.value) {
    rules2.value = [
      { required: isEmailEditable.value, message: '请输入邮箱', trigger: 'change' },
      {
        type: 'email',
        message: '请输入正确的邮箱',
      },
    ];
  } else {
    rules2.value = [];
  }
}

const openCreate = () => {
  title.value = '新增企业';
  formState.value.expireTimeDjs = undefined;
  isPwdEditable.value = true;
  isPhoneEditable.value = true;
  isEmailEditable.value = true;
  files.value = [];
  setPhoneRule();
  setEmailRule();
  getInfoData();
  visible.value = true;
};

const filesInDetail = ref();
const openDetail = async (tenantId, email) => {
  title.value = '查看详情';
  visible.value = true;
  initEyeTag();
  let record = await getEntDetail(tenantId);
  formState.value = record;
  registerTime.value = dayjs(record.registerTime).format('YYYY-MM-DD HH:mm:ss');
  if (formState.value.expireTime) {
    formState.value.expireTime = dayjs(record.expireTime).format('YYYY-MM-DD HH:mm:ss');
  } else {
    formState.value.expireTime = undefined;
  }

  filesInDetail.value = record.imagesList;
  tenantCode.value = record.code;
  formState.value.email = email;
};

const useDecrytion = async (decryptType: string) => {
  if (decryptType == 'password') {
    formState.value.password = await getDecrytion({ tenantCode: tenantCode.value, type: decryptType });
  }
  if (decryptType == 'phone') {
    phoneEyeTag.value = false;
    formState.value.phone = await getDecrytion({ tenantCode: tenantCode.value, type: decryptType });
  }
  if (decryptType == 'email') {
    emailEyeTag.value = false;
    formState.value.email = await getDecrytion({ tenantCode: tenantCode.value, type: decryptType });
  }
};
const eidtPassword = () => {
  formState.value.password = undefined;
  isPwdEditable.value = true;
};
const eidtPhone = () => {
  formState.value.phone = undefined;
  isPhoneEditable.value = true;
  setPhoneRule();
};
const eidtEmail = () => {
  formState.value.email = undefined;
  isEmailEditable.value = true;
  setEmailRule();
};
function getBase64(file: File) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}

const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');
const beforeUpload = (file) => {
  const { upFiles } = file;
  upFiles.push(file);
  files.value = upFiles;
};
const handleCancel = () => {
  previewVisible.value = false;
  previewTitle.value = '';
};
const handlePreview = async (file: UploadProps['fileList'][number]) => {
  if (!file.url && !file.preview) {
    file.preview = (await getBase64(file.originFileObj)) as string;
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
};
let deleteList = [];
const emit = defineEmits(['submitSuccess']);

const init = () => {
  nextTick(() => {
    if (visible.value == false) {
      formState.value = {} as UpdateEntMgtParam;
      files.value = [];
      isPwdEditable.value = false;
      isPhoneEditable.value = false;
      isEmailEditable.value = false;
      rules.value = [];
      rules2.value = [];
      deleteList = [];
      showMaxDate.value = false;
    }
  });
};
const close = () => {
  visible.value = false;
  formRef.value.clearValidate();
  emit('submitSuccess');
};

const handleRemove = (file) => {
  deleteList.push(file.id);
};
const submit = async () => {
  if (title.value == '编辑企业信息') {
    formRef.value.validate().then(async () => {
      if (formState.value.expireTimeDjs) {
        formState.value.expireTime = formState.value.expireTimeDjs.endOf('date').format('YYYY-MM-DD HH:mm:ss');
      }
      formState.value.registerTime = dayjs(formState.value.registerTime).format('YYYY-MM-DD HH:mm:ss');
      formState.value.id = recordId.value;
      delete formState.value.type;
      delete formState.value.isBuiltIn;
      if (isPwdEditable.value == false) {
        delete formState.value.password;
      }
      if (isPhoneEditable.value == false) {
        delete formState.value.phone;
      }
      if (isEmailEditable.value == false) {
        delete formState.value.email;
      }

      formState.value.deleteImagesList = deleteList;
      try {
        let res = await updateEntMgt(files.value, formState.value);

        if (res.data.code == 0) {
          message.success(ApiResultEnum.UPDATA_SUCCESS);
          emit('submitSuccess');
        } else {
          message.error(res.data.msg);
        }
      } finally {
        close();
      }
    });
  } else if (title.value == '新增企业') {
    formRef.value.validate().then(async () => {
      formState.value.expireTime = formState.value.expireTimeDjs.endOf('date').format('YYYY-MM-DD HH:mm:ss');
      await proxyRegister(files.value, formState.value).then((res) => {
        if (res.data.code !== 0) {
          message.error(res.data.msg);
        } else {
          message.success(ApiResultEnum.ADD_SUCCESS);
          emit('submitSuccess');
        }
      });
      close();
    });
  }
};

const formItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 14 },
};
defineExpose({ openEdit, openCreate, openDetail });
</script>
<style scoped>
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
